from helpers import updateInfo
from helpers import Visualization
import datetime
import os
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class MainPage(webapp.RequestHandler):
    """ Iser profile page (with compare between users) class """
    def get(self):
        
        user1 =users.get_current_user()
        user2=users.User(self.request.get('q'))
        user1_current=updateInfo.getCurrentUser(user1)
        q_1 = db.GqlQuery("SELECT * FROM TrendUsers WHERE tuser=:1",user2)
        q_1=q_1.fetch(1)
        
        # Make sure user is logged in, if not redirect to login page
        if not user1:
            self.redirect(users.create_login_url(self.request.uri))
            return

        graph_text=Visualization.createGraphForTwoUsers(user1,user2)
        change = (q_1[0].totalamount/100)
        
        printPercentage, fontColor, changeSign= updateInfo.getPerInfo(change)
        
        q_2 = db.GqlQuery("SELECT * FROM TrendUsers WHERE totalamount>:1",q_1[0].totalamount)
        rank = q_2.count()+1
        
        q_3 = db.GqlQuery("SELECT * FROM TrendUsers")
        totalusers = q_3.count()
        
        q_4 = db.GqlQuery("SELECT * FROM NewsFeeds WHERE buyer=:1",q_1[0].tuser)
        transactionNum = q_4.count()
        
        # if user click on himself, redirected to report
        if (user1 == user2):
            self.redirect("/report")
            
            
        newsfeeds = updateInfo.publishNewsFeeds (user1,user2)

        
        template_values = {
            'graph_text': graph_text,
            'current_user_totalamount': user1_current.totalamount,
            'current_user_bankamount': user1_current.bankamount, 
            'current_user_investamount': user1_current.totalamount-user1_current.bankamount,
            
            'user2_totalamount':q_1[0].totalamount,
            'user2_bankamount':q_1[0].bankamount,
            'user2_investamount':q_1[0].totalamount-q_1[0].bankamount,
            
            'user2' : user2.nickname().capitalize(),
            'newsfeeds' : newsfeeds,
            'logusername' : user1.nickname().capitalize(),
            'loginurl' : users.create_logout_url("/"),
            'changePercentage' : printPercentage,
            'fontColor': fontColor,
            'changeSign':changeSign,
            'rank': rank,
            'totalusers':totalusers,
            'transactionNum':transactionNum,
            'logintext' : 'Sign Out',
            'lastUpdate' : datetime.datetime.now().strftime("%d-%m-%Y"),
            'categoryName' : '%s Info Page' % user2.nickname().capitalize(),
            'setHead' : 1,
            'maincontent' : 'account_main.html',
            'headContent' : 'userprofile_head.html',
            'account_main_content' : 'userprofile_main.html'
            
        }
        path = os.path.join(os.path.dirname(__file__), updateInfo.controllersIndexPath)
        self.response.out.write(template.render(path, template_values))


application = webapp.WSGIApplication(
                                     [('/userProfile', MainPage)],
                                     debug=True)
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
